<template>
  <div class="detail-layout">
    <div class="detail-header webfont-Medium pointer" @click="handlerGoBack">
      <i class="el-icon-arrow-left "></i>
      <span>词库详情</span>
    </div>

    <el-card shadow="never">
      <div class="detail-main">
        <div class="search-box flex">
          <div class="lt">
            <div class="title-box ">
              <span v-show="!inputShow" class="pointer" @click="handleNameInputShow">{{ wordStoreName }}</span>
              <el-input
                v-show="inputShow"
                ref="input"
                v-model="inputStr"
                :value="wordStoreName"
                @blur="handleEnterOrBlur"
                @keyup.enter.native="handleEnterOrBlur"
              ></el-input>
            </div>
          </div>
          <div class="rt flex">
            <div class="input-box" style="max-width: 200px;">
              <el-input v-model.trim="searchStr" placeholder="搜索关键词" size="small" @keyup.enter.native="handleSearch">
                <i slot="suffix" class="el-input__icon el-icon-search" @click="handleSearch"></i>
              </el-input>
            </div>
            <em v-if="total>=5000" style="cursor: not-allowed;opacity: 0.8;" title="词库数量不得超过5000个">批量上传</em>
            <em v-else class="pointer" @click="dialogVisible=true">批量上传</em>

            <el-button type="success" :disabled="total>=5000" title="词库数量不得超过5000个" @click="putShow=true">
              <span style="font-size: 14px;line-height: 14px;">添加关键词</span>
            </el-button>
          </div>

        </div>

        <el-table
          ref="multipleTable"
          v-loading="loading"
          :data="tableData"
          tooltip-effect="dark"
          style="width: 100%"
          element-loading-text="数据加载中"
          @selection-change="handleSelecChange"
        >
          <el-table-column type="selection" width="55">
          </el-table-column>
          <el-table-column label="关键词" show-overflow-tooltip>
            <template slot-scope="scope">
              <span v-html="replaceKeyWord(scope.row.word,scope.row.matchType)"></span>
            </template>
          </el-table-column>

          <el-table-column prop="address" label="匹配模式" width="160">
            <template slot-scope="scope">{{ scope.row.matchType==='BROAD'?'模糊匹配':'精确匹配' }}</template>
          </el-table-column>
        </el-table>
        <div class="block" style="padding-top: 24px;display: flex;justify-content: flex-end;padding-bottom: 50px;">
          <el-pagination
            :current-page="queryData.page"
            :page-sizes="[10,20,30,40]"
            :page-size="10"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>

      </div>
    </el-card>
    <word-box
      ref="addWordBox"
      :visible.sync="putShow"
      title="关键词"
      width="1200px"
      @handleSub="handleSubKey"
      @expand-change="(data)=>{handleexpand(row,expanded)}"
    ></word-box>
    <up-load-words :is-negative="false" :visible.sync="dialogVisible" @handleAddWords="handleSubKey"></up-load-words>
    <hint-box v-if="selectList.length" :num="selectList.length">
      <div class="flex hint-rt">
        <template>
          <span v-if="brShow" class="pointer" @click="handleChangeType('EXACT')">改为精确匹配</span>
          <span v-else class="no-pointer">改为精确匹配</span>
        </template>
        <template>
          <span v-if="exShow" class="pointer" @click="handleChangeType('BROAD')">改为模糊匹配</span>
          <span v-else class="no-pointer">改为模糊匹配</span>
        </template>

        <span v-if="roleName==='admin'||roleName==='visitor'||userId==$route.query.uid" class="pointer" @click="handleDel">移除</span>
      </div>
    </hint-box>
  </div>
</template>
<script>
// import cellHeader from '@/components/cell-header.vue'
import hintBox from '@/components/hintBox/index.vue'
import wordBox from '@/components/word-box.vue'
import upLoadWords from '../components/upLoadWords.vue'

import {
  reallocate, // 词库重名验证
  UpWordsUser, // 修改词库
  getWordStoreInfo, // 获取详情
  addWordsToStore, // 添加关键词到词库
  delWordInStore, // 删除词库内的词语
  modifyWordInStore // 修改词库内的词语
} from '@/api/tool.js'

export default {
  name: '', // ·������
  components: {
    // cellHeader,
    hintBox,
    wordBox,
    upLoadWords

  },
  data() {
    return {
      wordStoreName: '', // 词库名称
      inputStr: '', // 词库新名称
      inputShow: false,
      titleStr: '',
      searchStr: '',
      queryData: {
        page: 1,
        size: 10,
        search: ''
      },
      putShow: false,
      dialogVisible: false,
      total: 0,
      selectList: [], // 多选的表格数据
      tableData: [],
      loading: false
    }
  },
  computed: {
    roleName() {
      return this.$store.state.user.userInfo.roleName
    },
    userId() {
      return this.$store.state.user.userInfo.userId
    },
    brShow() {
      if (this.selectList) {
        const index = this.selectList.findIndex(item => {
          return item.matchType === 'BROAD'
        })
        if (index > -1) return true
        return false
      }
      return false
    },
    exShow() {
      if (this.selectList) {
        const index = this.selectList.findIndex(item => {
          return item.matchType !== 'BROAD'
        })
        if (index > -1) return true
        return false
      }
      return false
    }
  },
  watch: {

  },
  // ������
  created() {},
  // ���غ�
  mounted() {
    this.wordStoreName = this.$route.query.name
    this.inputStr = this.$route.query.name
    if (!this.$route.query.id) {
      this.$router.go(-1)
    }
    if (this.$route.query.name) {
      this.titleStr = this.$route.query.name
    }
    this.getWordStoreInfo()
  },
  // ���ٺ�
  destroyed() {

  },

  // ����
  methods: {
    handlerGoBack() {
      this.$router.replace({
        name: 'wordicon'
      })
    },
    replaceKeyWord(word, type) {
      const str = word.replace(/\ /g, '&nbsp;')
      if (type === 'EXACT') return '[' + str + ']'
      return str
    },
    checkSelectable(row, index) {
      const str = row.word
      let num = 0
      this.tableData.forEach(item => {
        if (item.word === str) num++
      })
      if (num > 1) {
        return false
      } else {
        return true
      }
    },
    handleSizeChange(size) {
      this.queryData.size = size
      this.queryData.page = 1
      this.getWordStoreInfo()
    },
    handleCurrentChange(index) {
      this.queryData.page = index
      this.getWordStoreInfo()
    },
    handleSearch() {
      this.queryData.search = this.searchStr
      this.queryData.page = 1
      this.getWordStoreInfo()
    },
    async getWordStoreInfo() {
      this.loading = true
      try {
        const res = await getWordStoreInfo({
          ...this.queryData,
          wordUserId: this.$route.query.id
        })
        this.loading = false
        if (res.data.code * 1 === 20000) {
          this.total = res.data.data.total
          this.tableData = JSON.parse(JSON.stringify(res.data.data.list))
        } else {
          this.$message.closeAll()
          this.$message.error(res.data.message)
          if (res.data.message.indexOf('不存在') > -1) {
            this.$router.replace({
              name: 'wordicon'
            })
          }
        }
      } catch (err) {

      }
    },

    handleSelecChange(data) {
      this.selectList = JSON.parse(JSON.stringify(data))
    },

    async handleSubKey(data) {
      const list = data.map(item => {
        const obj = {}
        obj.wordUserId = this.$route.query.id
        obj.word = item.text
        obj.matchType = item.matchType
        return obj
      })
      const batch = [{
        wordUserId: this.$route.query.id,
        list
      }]

      const res = await addWordsToStore({
        batch
      })
      this.$message.closeAll()
      if (res.data.code * 1 === 20000) {
        this.$message({
          duration: 1500,
          message: res.data.message || '添加词成功',
          type: 'success'
        })
        this.queryData.page = 1
        this.getWordStoreInfo()
      } else {
        this.$message({
          duration: 1500,
          message: res.data.message || '添加词失败',
          type: 'error'
        })
      }
    },
    async handleChangeType(type) {
      // 修改匹配模式的操作
      try {
        const selectList = this.selectList.filter(item => {
          const index = this.selectList.findIndex(v => {
            return v.word === item.word && item.matchType !== v.matchType
          })
          return index < 0
        })
        if (!selectList.length) return false

        const list = selectList.map(item => {
          return {
            id: item.id,
            matchType: type
          }
        })
        const obj = {
          wordUserId: this.selectList[0].word_user_id,
          list
        }

        const res = await modifyWordInStore(obj)
        this.$message.closeAll()

        if (res.data.code * 1 === 20000) {
          this.$message({
            duration: 1500,
            message: res.data.message || '修改成功',
            type: 'success'
          })
          this.queryData.page = 1
          this.getWordStoreInfo()
        } else {
          this.$message.error(res.data.message || '修改失败')
        }
      } catch (err) {}
    },

    handleDel() {
      this.$confirm('一旦删除将不可恢复！', '确定要删除关键词？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        // type: 'warning'
      }).then(async() => {
        try {
          const arr = this.selectList.map(item => {
            return item.id
          })
          const obj = {
            wordUserId: this.selectList[0].word_user_id,
            teamId: this.$route.query.team || '',
            list: ''
          }
          obj.list = arr
          const res = await delWordInStore(obj)
          this.$message.closeAll()
          if (res.data.code * 1 === 20000) {
            this.$message({
              duration: 1500,
              message: res.data.message || '删除成功',
              type: 'success'
            })
            this.queryData.page = 1
            this.getWordStoreInfo()
          } else {
            this.$message.error(res.data.message || '删除失败')
          }
        } catch (err) {

        }
      })
    },
    handleNameInputShow() {
      this.inputShow = true
      this.$nextTick(() => {
        this.$refs['input'].focus()
      })
    },
    handleEnterOrBlur() {
      if (this.inputStr && this.inputStr !== this.wordStoreName && this.inputStr !== this.wordStoreName) {
        if (this.inputStr.length < 3 || this.inputStr.length > 20) {
          this.$message.closeAll()
          this.$message({
            duration: 1500,
            message: '词库名称长度为3到20位',
            type: 'error'
          })
          this.inputStr = this.wordStoreName
          this.inputShow = false
          return false
        }
        var regTextChar = /^[\u4e00-\u9fa5A-Za-z0-9\-\_]*$/
        const reg = new RegExp(/\s/g) // 清空字符自中所有空格
        if (!regTextChar.test(this.inputStr) || reg.test(this.inputStr)) {
          this.$message.closeAll()
          this.$message({
            duration: 1500,
            message: '词库名称只能由汉字,字母,数字,下划线,横杠组成',
            type: 'error'
          })
          this.inputStr = this.wordStoreName
          this.inputShow = false
          return false
        }

        reallocate({
          name: this.inputStr,
          teamId: this.$route.query.team || ''
        }).then(res => {
          if (res.data.code * 1 === 20000) {
            this.modifyWordStore()
          } else {
            this.$message.closeAll()
            this.$message({
              duration: 1500,
              message: '词库名称不可重复',
              type: 'error'
            })
          }
        })
      }
      this.$refs.input.blur()
      return this.inputShow = false
    },

    async modifyWordStore(data) {
      this.upLoding = true
      const wordUserId = this.$route.query.id
      const obj = {
        wordUserId,
        name: this.inputStr
      }
      try {
        const res = await UpWordsUser(obj)
        this.upLoding = false
        if (res.data.code * 1 === 20000) {
          this.$message.closeAll()
          this.$message({
            duration: 1500,
            message: res.data.message || '更改词库名称成功',
            type: 'success'
          })
          this.wordStoreName = this.inputStr
        } else {
          this.$message.closeAll()
          this.$message({
            duration: 1500,
            message: res.data.message || '更改词库名称失败',
            type: 'error'
          })
        }
      } catch (err) {}
    }
  }
}
</script>

<style scoped lang="scss">
  .detail-header {
    max-width: 200px;
    padding-bottom: 26px;
    font-size: 20px;
    line-height: 20px;
    color: #1D2129;

    i {
      margin-right: 12px;
      font-size: 18px;
      color: #4E5969;
      font-weight: 700;
    }
  }

  .detail-main {
    min-height: calc(100vh - 200px);
  }

  .search-box {
    margin-bottom: 27px;

    .lt {
      .title-box {
        span {
          display: inline-block;
          padding: 6px 8px;
          font-weight: 500;
          font-size: 20px;
          line-height: 20px;
          border: 1px solid transparent;

          &:hover {
            border-radius: 2px;
            border-color: #E0E2E7;
          }
        }

      }
    }

    .rt {
      justify-content: flex-end;
      font-size: 14px;
      line-height: 14px;

      em {
        margin: 0 24px
      }

      ::v-deep span {
        font-size: 14px;
        line-height: 14px;
      }
    }
  }

  .hint-rt {
    justify-content: flex-end;

    span {
      margin-left: 24px;
      color: #24BEBE;
    }
  }

  .no-pointer {
    cursor: not-allowed;
    opacity: 0.8;
    color: #999;
  }
</style>
